#!/usr/bin/perl
#########################################################################
# NAME: readings.cgi
# DESC: 
# HIST:
#       20mar2008  GJ  ORIGINAL VERSION
#


use meterDB;
use CGI qw/:standard/;
use strict;

my $dbh = meterDB->new();

my $query = CGI->new();

print $query->header('text/html');

print <<EOF;
<html>
<head>
<title>Meter Readings Viewer</title>
<LINK REL=stylesheet HREF="property.css" TYPE="text/css">
<meta http-equiv="pragma" content="no-cache">
</head>
<body bgcolor=white fgcolor=black>
EOF

if (param('m') eq 'meter_chooser')
{
    meter_list();
}
elsif (param('m') eq 'select_menu')
{
    select_menu();
}
elsif (param('m') eq 'show')
{
    show_table() if (param('sm') eq 'table');
    show_graph() if (param('sm') eq 'graph');
}
else
{
    meter_list();
}

print <<EOF;
</body>
</html>
EOF




##############################################################################
# NAME: meter_list
# DESC: presents a list of all meters as a table.  Includes liks to the
#        select menu for each meter
# HIST: 20mar2008  GJ  ORGINAL VERSION
#
sub meter_list
{
    my $meters = $dbh->get_generic_sql('meters','id','select * from meters');
    my $datacount = scalar keys %{$meters};
    print <<EOF;
<p class=pageheader>Meter List ($datacount entries)</p>
<p><a href="readings.cgi">Choose Meter</a></p>
<form method=POST action=readings.cgi>
<input type=hidden name=m value=meter_chooser>
<input type=hidden name=sm value=delete>
EOF

    print('<table border=0 cellpadding=0 cellspacing=0>',
          '<tr><th align=left>ID</th><th width=15>&nbsp;</th>',
          '<th align=left>Description</th><th width=15>&nbsp;</th>',
          '<th align=left>Input No.</th><th width=15>&nbsp;</th>');

    foreach my $id (sort keys %{$meters})
    {
        printf('<tr><td><a href="%s">%s</a></td>' . 
               '<td></td><td>%s</td><td></td>' . 
               '<td>%s</td><td></td><td>%s</td></tr>',
               "readings.cgi?m=select_menu&id=$id",
               $meters->{$id}->{id},
               $meters->{$id}->{description},
               $meters->{$id}->{input});
    }
}


#////////////////////////////////////////////////////////////////////////////////////////
#// NAME: select_menu
#// DESC: Display the data select menu for a particular meter.
#// HIST: 20jan2008  GJ ORIGINAL VERSION

sub select_menu
{
    my $meterrecord = $dbh->get_generic_single('meters',{'id' => param('id')});
    
    # Find date of first record in table.
    my $query = "select min(time) from readings where meter = $meterrecord->{id}";
    my $result = $dbh->get_generic_sql('meters','id',$query);
    my $mindate;
    while ( my ($key, $value) = each(%$result) ) {
	while ( my ($key2, $value2) = each(%$value)) {
	    $mindate = $value2;
	}
    }
    
# Find date of last record in table
    $query = "select max(time) from readings where meter = $meterrecord->{id}";
    $result = $dbh->get_generic_sql('meters','id',$query);
    my $maxdate;
    while ( my ($key, $value) = each(%$result) ) {
	while ( my ($key2, $value2) = each(%$value)) {
	    $maxdate = $value2;
	}
    }
    print "mindate=",$mindate," maxdate=",$maxdate,"\n";
    
    
    print <<EOF;
    <p class=pageheader>\u Meter</p>
	<p><a href="readings.cgi">List Meters</a>&nbsp;|&nbsp</p>
	<form method=POST action=readings.cgi>
	<input type=hidden name=m value=show>
	<input type=hidden name=id value="$meterrecord->{id}">
	<h1>Select Data Range<h1>
	<table border=1 cellspacing=0 cellpadding=0>
	<tr>
	<td class=fieldlabel>Meter Description</td>
	<td>$meterrecord->{description}></td>
	</tr>
	<tr>
	<td class=fieldlabel>Start Date (yyyy-mm-dd)</td>
	<td><input type=text name=mindate size=30 value="$mindate"></td>
	</tr>
	<tr>
	<td class=fieldlabel>End Date (yyyy-mm-dd)</td>
	<td><input type=text name=maxdate size=30 value="$maxdate"></td>
	</tr>
	<tr>
	<td class=fieldlabel>Summarise</td>
	<td><input type="radio" name="groupby" value="none" checked>All Data<br>
	<input type="radio" name="groupby" value="daily">Daily<br>
	</td>
	</tr>
	<tr>
	<td class=fieldlabel>Output Type</td>
	<td><input type="radio" name="sm" value="table" checked> Table<br>
	<input type="radio" name="sm" value="graph"> Graph<br>
	</td>
	</tr>
	</table>
	<input type=submit value="Submit"><BR>
EOF
    }

###########################################################
# NAME: data_select_form
# DESC: Displays a form to allow the user to select the meter,
#       time range and grouping of the data to be displayed.
# HIST: 22mar2008 GJ ORIGINAL VERSION
#
#data_select_form {
#}


############################################
# NAME: show_table
# DESC: displays the meter readings as a table.
#       Expects the following parameters to be set.
#       id = meter id.
#       mindate = start date of required output (yyyy-mm-dd)
#       maxdate = end date of required output (yyyy-mm-dd)
#       groupby = none (show all date), daily (show one reading per day)
# HIST: 20mar2008  GJ  ORIGINAL VERSION
#
sub show_table {

    my $id = param('id');
    my $mindate = param('mindate');
    my $maxdate = param('maxdate');
    my $groupby = param('groupby');
    
    my $meterrecord = $dbh->get_generic_single('meters',{'id' => $id});
    my $units = $meterrecord->{'unit'};
    my $desc  = $meterrecord->{'description'};

    print <<EOF;
    <h1 class=pageheader>Readings from Meter $desc</h1>
	<p>Readings recorded between $mindate and $maxdate.</p>
	<p><a href="readings.cgi">Select Meter</a>&nbsp;|&nbsp
	<a href="readings.cgi?m=select_menu&id=$id">Select Data Range</a>&nbsp;|&nbsp</p>
	<p>Filter Data: 
	<a href="readings.cgi?m=show&sm=table&id=$id
                                     &mindate=$mindate&maxdate=$maxdate
                                     &groupby=none">
				     All Data</a>&nbsp;|&nbsp
	<a href="readings.cgi?m=show&sm=table&id=$id
                                     &mindate=$mindate&maxdate=$maxdate
                                     &groupby=daily">
				     Daily Summary</a>&nbsp;|&nbsp
	<a href="readings.cgi?m=show&sm=table&id=$id
                                     &mindate=$mindate&maxdate=$maxdate
                                     &groupby=$groupby">
				     Refresh Data</a>
     </p>
<input type=hidden name=m value=show>
<input type=hidden name=id value="param('id')">
EOF



    my $query;
    if ( $groupby eq 'none' ) {
	$query = "select time, reading, julianday(time) as jtime ".
	    "         from readings ".
	    "     where meter = $id ".
	    "         and time>=date('$mindate') ".
	    "         and time<=date('$maxdate')".
	    "     order by jtime";
    } elsif ( $groupby eq 'daily' ) {
	$query = "select date(time,'start of day') as time, ".
	    "         min(reading) as reading, ".
	    "         julianday(time,'start of day') as jtime ".
	    "         from readings ".
	    "     where meter = $id ".
	    "         and time>=date('$mindate') ".
	    "         and time<=date('$maxdate')".
	    "     group by date(time, 'start of day')".
	    "     order by jtime";
    }
#    print "<p>query=",$query,"</p>\n";
    
    my $result = $dbh->get_generic_sql('readings',undef,$query);
    
    
    my $prev_r = -1; # previous reading
    my $prev_t = 0; # previous time
    my $prev_jt = 0; # previous julian time
    print "<table border=1>".
	"    <tr>".
	"        <th>Date/Time</th>".
	"        <th>Reading ($units)</th>".
	"        <th>Rate ($units/day)</th>".
	"    </tr>\n";
    foreach (@{$result})
    {
	my $rate;
	my $cur_t = $_->{'time'};
	my $cur_jt = $_->{'jtime'};
	my $cur_r = $_->{'reading'};
	if ($prev_r == -1) {
	    $prev_r = $cur_r;
	    $prev_t = $cur_t;
	    $prev_jt = $cur_jt;
	}
	if ($prev_jt == $cur_jt ) {
	    $rate = 0;
	} else {
	    $rate = ($cur_r - $prev_r)/($cur_jt - $prev_jt);	    
	}
	$prev_r = $cur_r;
	$prev_t = $cur_t;
	$prev_jt = $cur_jt;

	printf "<tr>".
	    "     <td>%s</td>".
	    "     <td align=\'right\'>%5.2f</td>".
	    "     <td align=\'right\'>%5.2f</td>".
	    "   </tr>\n",
	    $cur_t, $cur_r, $rate;
    }
    
    
}


